/**
 * 部门路由
 * Created by benben on 14-9-4.
 */

var express = require('express');
var router = express.Router();
var Department = require('../../modules/system/department');
var Page = require('../../utils/page/Page');
var DepartmentService = require('../../service/system/DepartmentService');

var service = new DepartmentService();

router.route('/departments')
    .get(function(req, res) {
        //查询所有
        var department = new Department(req.query);
        var query = new Page({
            start : req.query.start,
            limit : req.query.limit,
            conditionObj : department
        });
        service.findPage(query,function(err,page){
            res.json(page);
        });
    })
    .post(function(req, res) {
        //增加
        var department = new Department(req.body);
        var arr = req.body.upDepartment.split('=');
        department.upDepartment._id = arr[0];
        department.upDepartment.departmentName = arr[1];
        department.status = 1;

        service.save(department,function(err){
            if (err) {
                res.send({ success:false,'info':err});
            }

            res.send({ success:true,'info':'保存成功'});
        });
    });
router.route('/departments/:id')
    .get(function(req, res) {
        //根据ID查询
        service.getById(req.params.id,function(err,page){
            if (err) {
                res.send({ success:false,'info':err});
            }
            res.json(page);
        });
    })
    .put(function(req,res) {
        //根据ID修改
        var arr = req.body.upDepartment.split('=');
        var upDepartment = {
            _id : arr[0],
            departmentName : arr[1]
        };
        req.body.upDepartment = upDepartment;

        service.updateById(req.params.id, req.body, function (err) {
            if (err) {
                res.send({ success: false, 'info': err});
            }
            res.send({ success: true, 'info': '修改成功'});
        });
    });

router.route('/departments/stop/:id').put(function(req, res) {
    //停用部门
    service.stopById(req.params.id,function(err){
        if (err) {
            res.send({ success: false, 'info': err});
        }else{
            res.send({ success: true, 'info': '操作成功'});
        }
    });
});

/**
 * 获取部门树
 */
router.route('/tree').get(function(req, res) {
    service.getTreeJSON(function(docs){
        res.send(docs);
    });
});


module.exports = router;